<template>
  <div>
    <Breadcrumb :bread-item-name="['权限管理','角色列表']"></Breadcrumb>
    <el-card>
      <!--      角色列表区域-->
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <!--      角色列表数据-->
      <el-table :data="rolesList" border stripe>
        <el-table-column type="expand" label="...">
          <template slot-scope="scope">
            <el-row :class="['bdbottom',i1===0?'bdtop':'','vcenter']" v-for="(item1,i1) in scope.row.children"
                    :key="item1.id">
              <!--              左侧一级权限占用5列-->
              <el-col :span="5">
                <el-tag closable @close="removeRightsById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row :class="[i2===0?'':'bdtop','vcenter']" v-for="(item2,i2) in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag closable @close="removeRightsById(scope.row,item2.id)" type="success">{{item2.authName}}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag closable @close="removeRightsById(scope.row,item3.id)" type="warning"
                            v-for="(item3) in item2.children" :key="item3.id">
                      {{item3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini">删除</el-button>
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRoleDialog(scope.row)">分配权限
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!--    分配权限对话框-->
    <el-dialog
        title="修改用户信息"
        :visible.sync="setRightDialogVisible"
        width="40%"
        @close="setRightDialogClosed"
    >
      <el-tree ref="treeRef" :data="rightsList" :props="treeProps" show-checkbox
               node-key="id" default-expand-all :default-checked-keys="defKeys"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
       </span>
    </el-dialog>
  </div>
</template>

<script>
import Breadcrumb from '@/components/Breadcrumb'

export default {
  name: 'Roles',
  data() {
    return {
      rolesList: [],
      rightsList: [],
      setRightDialogVisible: false,
      //树形控件属性绑定字段
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      //默认选中的节点数组
      defKeys: [],
      //即将分配权限的角色id
      roleId: ''
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    async getRolesList() {
      let { data: result } = await this.$http.get('/roles')
      if (result.meta.status !== 200) return this.$message.error('获取角色列表失败')
      this.rolesList = result.data
    },
    async removeRightsById(role, rightId) {
      let removeRightsTag = await this.$confirm('是否删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      console.log(removeRightsTag)
      if (removeRightsTag !== 'confirm') return this.$message.info('已取消')
      let {
        data: result
      }
        = await this.$http.delete(`/roles/${role.id}/rights/${rightId}`)
      if (result.meta.status !== 200) return this.$message.error('删除权限失败,请稍后再试')
      // this.getRolesList()
      //如果在掉拉取数据,会触发整个list的重新渲染
      role.children = result.data
      this.$message.success('删除成功')
    },
    async showSetRoleDialog(role) {
      this.roleId = role.id
      this.getLeafKeys(role, this.defKeys)
      this.setRightDialogVisible = true
      let { data: result } = await this.$http.get('/rights/tree')
      if (result.meta.status !== 200) return this.$message.error('获取权限数据失败')
      this.rightsList = result.data
    },
    //  定义递归函数,把角色中的三级权限保存到数组中
    getLeafKeys(node, arr) {
      //如果当前node节点不包含children属性,则是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    setRightDialogClosed() {
      this.defKeys = []
    },
    async allotRights() {
      const keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()]
      const idStr = keys.join(',')
      let { data: res } = await this.$http.post(`/roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) return this.$message.error('分配权限失败')
      this.$message.success('分配权限成功')
      this.getRolesList()
      this.setRightDialogVisible = false
    }
  },
  components: {
    Breadcrumb
  }
}
</script>

<style scoped>
  .el-tag {
    margin: 7px;
  }

  .bdbottom {
    border-bottom: 1px solid #eee;
  }

  .bdtop {
    border: 1px solid #eee;
  }

  .vcenter {
    display: flex;
    align-items: center;
  }
</style>